package com.estore.network;

import com.estore.service.ProductService;
import com.estore.entity.Product;
import java.io.*;
import java.net.*;
import java.util.List;

public class EStoreServer {
    private ProductService productService;
    private ServerSocket serverSocket;
    private static final int PORT = 8888;
    private boolean isRunning;

    public EStoreServer() {
        this.productService = new ProductService();
        this.isRunning = true;
    }

    public void start() {
        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("服务器已启动，监听端口: " + PORT);
            System.out.println("服务器地址: " + InetAddress.getLocalHost().getHostAddress());

            while (isRunning) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到客户端连接: " + clientSocket.getInetAddress().getHostAddress());

                // 为每个客户端创建新线程处理
                new ClientHandler(clientSocket).start();
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败: " + e.getMessage());
        } finally {
            stopServer();
        }
    }

    private void stopServer() {
        isRunning = false;
        try {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
        } catch (IOException e) {
            System.err.println("关闭服务器时出错: " + e.getMessage());
        }
        System.out.println("服务器已停止");
    }

    // 内部类，处理客户端请求
    private class ClientHandler extends Thread {
        private Socket clientSocket;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        @Override
        public void run() {
            handleClient(clientSocket);
        }

        private void handleClient(Socket clientSocket) {
            try (ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
                 ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream())) {

                // 设置超时时间，避免客户端长时间不发送请求
                clientSocket.setSoTimeout(30000);

                // 读取客户端请求
                String request = (String) input.readObject();
                System.out.println("接收到客户端请求: " + request);

                // 根据请求处理业务逻辑
                Object response = processRequest(request);

                // 发送响应给客户端
                output.writeObject(response);
                output.flush();
                System.out.println("响应已发送给客户端: " + clientSocket.getInetAddress().getHostAddress());

            } catch (SocketTimeoutException e) {
                System.err.println("客户端请求超时: " + e.getMessage());
            } catch (IOException | ClassNotFoundException e) {
                System.err.println("处理客户端请求时出错: " + e.getMessage());
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    System.err.println("关闭客户端连接时出错: " + e.getMessage());
                }
            }
        }

        private Object processRequest(String request) {
            try {
                switch (request) {
                    case "GET_ALL_PRODUCTS":
                        return productService.getAllProducts();
                    case "GET_SERVER_INFO":
                        return "EStore Server v1.0 - Running on port " + PORT;
                    // 可以在这里添加更多的请求处理逻辑
                    default:
                        return "错误: 未知请求 '" + request + "'";
                }
            } catch (Exception e) {
                return "错误: 处理请求时发生异常 - " + e.getMessage();
            }
        }
    }

    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();
        server.start();
    }
}
